package pl.diagnoser.server.persistance.dao;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import pl.diagnoser.client.dto.EstimateDTO;
import pl.diagnoser.client.dto.ObjectHistoryViewer;
import pl.diagnoser.server.persistance.map.Estimate;
import pl.diagnoser.server.persistance.map.Symptom;
import pl.diagnoser.server.persistance.tools.HibernateUtil;

public class EstimateDao implements Serializable {

        private static final long serialVersionUID = 1L;
        
        @SuppressWarnings("unchecked")
        public List<ObjectHistoryViewer> getEstimateForObjects(Long id) {
        	List<ObjectHistoryViewer> objectHistoryViewer = new ArrayList<ObjectHistoryViewer>();
        	SymptomDao symptomDao = new SymptomDao();
        	
        	Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction(); 
            List<Estimate> estimate;
            
            if(id != null)
            	estimate = session.createCriteria(Estimate.class).add(Restrictions.eq("estimateObject", new ObjectsDao().getObject(id))).list();
            else
            	estimate = session.createQuery("from Estimate").list();
            	
            if(estimate != null && estimate.size() > 0) {
	            for(Estimate est : estimate) {
	            	List<Symptom> symptoms = symptomDao.getSymptomsForEstimate(est);
	            	objectHistoryViewer.add(new ObjectHistoryViewer( createEstimateDTO(est), symptomDao.createSymptomDTO(symptoms)));
	            }
            }
            
            session.getTransaction().commit();
    		session.close();
            return objectHistoryViewer;
        }
        
        public Long saveEstimate(Estimate estimate, Session session) {
                Long generatedId = (Long) session.save(estimate);
                return generatedId;
        }
         
        public EstimateDTO createEstimateDTO(Estimate estimate) {
                ObjectsDao objectDao = new ObjectsDao();
                DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                
                return new EstimateDTO( formatter.format(estimate.getEstDate()), 
                                        objectDao.createObjectsDTO(estimate.getEstimateObject()), 
                                        estimate.getDefect(), 
                                        estimate.getId());
        }
        
}